{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def int2bytes(tensor, bits=2):\n",
    "    bool_tensors = [torch.zeros_like(tensor, dtype=torch.bool) for _ in range(bits)]     # construct a list of boolean tensor\n",
    "    for i, bit in enumerate(reversed(range(bits))):\n",
    "        idx = tensor >= (2**bit)\n",
    "        bool_tensors[i][idx] = True\n",
    "        tensor = tensor - (2**bit) * idx\n",
    "    return bool_tensors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def bytes2int(bool_tensors):\n",
    "    tensor = torch.zeros_like(bool_tensors[0], dtype=torch.int)\n",
    "    for i, bt in enumerate(reversed(bool_tensors)):\n",
    "        tensor += (2 ** i) * bt\n",
    "    return tensor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = torch.randint(4, (5, 6))\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bool_a = int2bytes(a, bits=2)\n",
    "for ba in bool_a:\n",
    "    print(ba)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "re_a = bytes2int(bool_a)\n",
    "print(re_a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# more complicated test\n",
    "b = torch.randint(16, (10, 20, 30))\n",
    "re_b = bytes2int(int2bytes(b, bits=4))\n",
    "print(torch.sum(torch.abs(b-re_b)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
